package com.letv.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Environment;

public class LetvLogApiTool {
    private final String PATH = Environment.getExternalStorageDirectory() + "/letv/exceptionInfo/";

    private File dir = new File(PATH);
    private File file = null;

    private final int POOL_SIZE = 3;
    private int cpuNums = Runtime.getRuntime().availableProcessors();
    private ExecutorService executor = Executors.newFixedThreadPool(cpuNums * POOL_SIZE);

    private static LetvLogApiTool mLetvLogTool = null;

    public final String EXCEPTIONINFO_NAME = "exceptionInfo.log";

    public synchronized static LetvLogApiTool getInstance() {
        if (mLetvLogTool == null) {
            mLetvLogTool = new LetvLogApiTool();
        }
        return mLetvLogTool;
    }

    private double timeOutValue = 1.5;

    public double getTimeOutValue() {
        return timeOutValue;
    }

    public void setTimeOutValue(double timeOutValue) {
        this.timeOutValue = timeOutValue;
    }

    /**
     * 检查是否装在sd卡
     * 
     * @return
     */
    private static boolean sdCardMounted() {
        final String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED) &&
                !state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    }

    /**
     * 返回当前时间字符串
     * 
     * @return
     */
    private static String getTimeStamp() {
        // 按自定义格式SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatTime.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        Date currentTime = new Date(System.currentTimeMillis());
        String tt = formatTime.format(currentTime);
        return tt;
    }

    public static void createExceptionInfo(int errorType, String errorDes, String requestUrl, String responseData) {
        LetvLogApiTool.getInstance().saveExceptionInfo(
                getTimeStamp() + " errorType = " + errorType + "  requestUrl =" + requestUrl + errorDes
                        + "\n\r  responseData=" + responseData);
    }

    /**
     * 播放log本地存储
     * 
     * @param logType
     * @param vid
     * @param logDesc
     */
    public static void createPlayLogInfo(String logType, String vid, String logDesc) {
        LetvLogApiTool.getInstance().saveExceptionInfo(
                logType + " time=" + getTimeStamp() + " vid=" + vid + " description=" + logDesc);
    }

    public File getExceptionFile() {
        return new File(dir, EXCEPTIONINFO_NAME);
    }

    /**
     * 存储文件数据
     * 
     * @param data
     */
    public void saveExceptionInfo(String data) {
        if (!sdCardMounted()) {
            return;
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file = new File(dir, EXCEPTIONINFO_NAME);
        if (file.exists() && file.length() > 1024 * 1024) {
            file.delete();
        }
        try {
            file.createNewFile();
            executor.execute(new Handler(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Handler implements Runnable {

        private String data;

        public Handler(String data) {
            this.data = data;
        }

        @Override
        public void run() {
            synchronized (file) {
                BufferedReader stringReader = null;
                FileWriter fileWriter = null;
                try {
                    stringReader = new BufferedReader(new StringReader(data));
                    fileWriter = new FileWriter(file, true);
                    String line = null;
                    while ((line = stringReader.readLine()) != null) {
                        LogInfo.log("Emerson", "-----line = " + line);
                        fileWriter.write(line);
                        fileWriter.write("\r\n");
                    }
                    stringReader.close();
                    fileWriter.flush();
                    fileWriter.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        stringReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
